﻿using Styx.Plugins;
using Styx.WoWInternals;
using Styx.CommonBot;
using Styx.Common;
using System;
using System.IO;
using System.Collections.Generic;
//using System.Timers;
using System.Text.RegularExpressions;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using GreyMagic;
using System.Net.Sockets;
using System.Net;
using System.Text;



namespace BuddyCon
{
    public class BuddyCon : HBPlugin
    {
        Timer times;
        String wowpath;
        public static Boolean on = false;
        public static Boolean isInit=false;

        DateTime lastUpdate;
        DateTime startTime;


        public override string Author
        {
            get { return "thalord"; }
        }

        public override string Name
        {
            get { return "BuddyCon"; }
        }

        public override void Pulse() {
            //if (BuddyConSettings.Instance.debug) Logging.Write(string.Format("[bC]: pulse"));
            updater();
        }

        public override System.Version Version
        {
            get { return new System.Version(1, 0, 66); }
        }

 

        public override void OnButtonPress()
        {
            new FormSettings().ShowDialog();

        }
        public override bool WantButton { get { return true; } }
        public override string ButtonText { get { return "Settings"; } }
        public override void Initialize()
        {
            if (!BuddyCon.isInit)
            {
                Logging.Write(string.Format("[bC]: Version {0} initalized", Version.ToString()));

                on = true;
                Chat.Say += Chat_Say;
                Chat.Yell += Chat_Yell;
                Chat.Whisper += Chat_Whisper;
                Chat.Party += Chat_Party;
                Chat.PartyLeader += Chat_Party;
                Chat.Guild += Chat_Guild;
                Chat.Emote += Chat_Emote;
                Chat.Battleground += Chat_BG;
                Chat.BattlegroundLeader += Chat_BG;
                Chat.Raid += Chat_Raid;
                Chat.RaidLeader += Chat_Raid;

                //Styx.CommonBot.BotEvents.Player.OnPlayerDied += onDead;
                //Styx.CommonBot.BotEvents.Player.OnLevelUp += onLevel;
                //Styx.CommonBot.BotEvents.Player.OnMobKilled += onMobkill;

                //Lua.Events.AttachEvent("CHAT_MSG_MONEY", Loot);
                //Lua.Events.AttachEvent("CHAT_MSG_LOOT", Loot);
                //Lua.Events.AttachEvent("CHAT_MSG_COMBAT_XP_GAIN", Xp);

                Styx.CommonBot.BotEvents.OnBotStopped += onStop;
                Styx.CommonBot.BotEvents.OnBotStarted += onStart;

                Lua.Events.AttachEvent("GUILDBANKFRAME_OPENED", GbankUpdate);
                Lua.Events.AttachEvent("GUILDBANK_UPDATE_MONEY", GbankUpdate);

                Lua.Events.AttachEvent("CHAT_MSG_BN_WHISPER", BNetWhisper);
                Lua.Events.AttachEvent("GMRESPONSE_RECEIVED", GMResponse);

                data = new Dictionary<string, string>();
                data.Add("version", Version.ToString());
                data.Add("name", "");
                data.Add("level", "");
                data.Add("xp", "");
                data.Add("xp_needed", "");
                data.Add("chat_message", "");
                data.Add("chat_type", "");
                data.Add("chat_from", "");
                data.Add("screen", "");
                data.Add("nodeh", "");
                data.Add("runningtime", "");
                data.Add("xph", "");
                data.Add("timeolevel", "");
                data.Add("kills", "");
                data.Add("killsh", "");
                data.Add("honor", "");
                data.Add("honorh", "");
                data.Add("death", "");
                data.Add("deathh", "");
                data.Add("bgwin", "");
                data.Add("bglost", "");
                data.Add("server", "");
                data.Add("gbankmoney", "");
                //using (Styx.StyxWoW.Memory.AcquireFrame())
                //{
                wowpath = Styx.StyxWoW.Memory.Process.MainModule.FileName.Substring(0, Styx.StyxWoW.Memory.Process.MainModule.FileName.Length - 8);

                // init start values

                data["level"] = Convert.ToInt32(Styx.StyxWoW.Me.Level).ToString();
                data["apikey"] = BuddyConSettings.Instance.apikey;
                data["server"] = Styx.StyxWoW.Me.RealmName.ToString();


                data["name"] = Styx.StyxWoW.Me.Name.ToString();
                if (Convert.ToInt32(Styx.StyxWoW.Me.Experience) > 0 && Convert.ToInt32(Styx.StyxWoW.Me.Experience) <= Int32.MaxValue) data["xp"] = Convert.ToInt32(Styx.StyxWoW.Me.Experience).ToString();
                if (Convert.ToInt32(Styx.StyxWoW.Me.NextLevelExperience) > 0 && Convert.ToInt32(Styx.StyxWoW.Me.NextLevelExperience) >= Int32.MaxValue) data["xp_needed"] = Convert.ToInt32(Styx.StyxWoW.Me.NextLevelExperience).ToString();
                //}
                // setup timer to send updates
                //times.Elapsed += new ElapsedEventHandler(updater);
                //times.Interval = 15000;
                //times.Enabled = true;
                lastUpdate = DateTime.Now;
                startTime = DateTime.Now;

                times = new Timer(timesUpdater, data, 0, 25000);


                if (BuddyConSettings.Instance.pdebug) Logging.Write(string.Format("[bC]: init done"));

                BuddyCon.isInit = true;

            }
        }
        
        private void GbankUpdate(object sender, LuaEventArgs args)
        {
            data["gbankmoney"] = Convert.ToUInt32(Styx.WoWInternals.Lua.GetReturnVal<Int32>("return GetGuildBankMoney()", 0)).ToString();
        }

        [DllImport("user32.dll")]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);


        public override void Dispose()
        {
            base.Dispose();
            if (BuddyConSettings.Instance.pdebug) Logging.Write(string.Format("[bC]: start dispose"));

            on = false;

            Chat.Say -= Chat_Say;
            Chat.Yell -= Chat_Yell;
            Chat.Whisper -= Chat_Whisper;
            Chat.Party -= Chat_Party;
            Chat.PartyLeader -= Chat_Party;
            Chat.Guild -= Chat_Guild;
            Chat.Emote -= Chat_Emote;
            Chat.Battleground -= Chat_BG;
            Chat.BattlegroundLeader -= Chat_BG;
            Chat.Raid -= Chat_Raid;
            Chat.RaidLeader -= Chat_Raid;

            Styx.CommonBot.BotEvents.Player.OnPlayerDied -= onDead;
            Styx.CommonBot.BotEvents.Player.OnLevelUp -= onLevel;
            Styx.CommonBot.BotEvents.Player.OnMobKilled -= onMobkill;

            //Lua.Events.DetachEvent("CHAT_MSG_LOOT", Loot);
            //Lua.Events.DetachEvent("CHAT_MSG_COMBAT_XP_GAIN", Xp);
            //Lua.Events.DetachEvent("SCREENSHOT_SUCCEEDED", uploadscreen);


            Lua.Events.DetachEvent("GUILDBANKFRAME_OPENED", GbankUpdate);
            Lua.Events.DetachEvent("GUILDBANK_UPDATE_MONEY", GbankUpdate);

            Lua.Events.DetachEvent("CHAT_MSG_BN_WHISPER", BNetWhisper); 
            Lua.Events.DetachEvent("GMRESPONSE_RECEIVED", GMResponse);	

            Styx.CommonBot.BotEvents.OnBotStopped -= onStop;
            Styx.CommonBot.BotEvents.OnBotStarted -= onStart;

            data = new Dictionary<string, string>();

            data["version"] = "";
            data["name"] = "";
            data["level"] = "";
            data["xp"] = "";
            data["xp_needed"] = "";
            data["chat_message"] = "";
            data["chat_type"] = "";
            data["chat_from"] = "";
            data["screen"] = "";
            data["nodeh"] = "";
            data["runningtime"] = "";
            data["xph"] = "";
            data["timeolevel"] = "";
            data["kills"] = "";
            data["killsh"] = "";
            data["honor"] = "";
            data["honorh"] = "";
            data["death"] = "";
            data["deathh"] = "";
            data["bgwin"] = "";
            data["bglost"] = "";
            data["server"] = "";

            //times.Elapsed -= new ElapsedEventHandler(updater);
            //times.Enabled = false;
            //if(times.Enabled)
                times.Dispose(); 
            Logging.Write("[bC]: Dispose ");
            BuddyCon.isInit = false;

            if (BuddyConSettings.Instance.pdebug) Logging.Write(string.Format("[bC]: end dispose"));


        }

        

        private Dictionary<string, string> data ;

        private Dictionary<string, string> status = new Dictionary<string, string>();


        public BuddyCon()
        {
        }

        #region onX
        private void onMobkill(BotEvents.Player.MobKilledEventArgs args)
        {
        }

        private void onStart(EventArgs args)
        {
            startTime = DateTime.Now;
            // if(times != null)
            //    times.Dispose(); 
            if (BuddyConSettings.Instance.pdebug) Logging.Write(string.Format("[bC]: start onStart"));

            //using (Styx.StyxWoW.Memory.AcquireFrame()){
                Styx.CommonBot.BotEvents.Player.OnPlayerDied += onDead;
                Styx.CommonBot.BotEvents.Player.OnLevelUp += onLevel;
                //Styx.CommonBot.BotEvents.Player.OnMobKilled += onMobkill;

                data["name"] = Styx.StyxWoW.Me.Name.ToString();
                data["server"] = Styx.StyxWoW.Me.RealmName.ToString();
                data["gbankmoney"] = Convert.ToUInt32(Styx.WoWInternals.Lua.GetReturnVal<Int32>("return GetGuildBankMoney()", 0)).ToString();

            //}

            Logging.Write("[bC]: Bot started");
            if (BuddyConSettings.Instance.notfStart)
                Util.sendToProwl("Bot", "Bot started", data["name"], data["server"]);

            if(!status.ContainsValue( "Bot started"))
                status.Add("message", "Bot started");
            //send(data);
            if (BuddyConSettings.Instance.pdebug) Logging.Write(string.Format("[bC]: end onStart"));


        }

        private void onStop(EventArgs args)
        {
            //Thread thread = new Thread(delegate() { 
           
            if (BuddyConSettings.Instance.pdebug) Logging.Write(string.Format("[bC]: onstop start ", on));

            //times = new Timer(timesUpdater, data, 0, 15000);
            //using (Styx.StyxWoW.Memory.AcquireFrame()){
                Styx.CommonBot.BotEvents.Player.OnPlayerDied -= onDead;
                Styx.CommonBot.BotEvents.Player.OnLevelUp -= onLevel;
                //Styx.CommonBot.BotEvents.Player.OnMobKilled -= onMobkill;

                //Lua.Events.DetachEvent("SCREENSHOT_SUCCEEDED", uploadscreen);
            //}
            Logging.Write("[bC]: Bot stopped");
            if (BuddyConSettings.Instance.notfStop)
                Util.sendToProwl("Bot", "Bot stopped", data["name"], data["server"]);
            if (!status.ContainsValue("Bot stopped"))
                status.Add("message", "Bot stopped");
            //send(data);
            if (BuddyConSettings.Instance.pdebug) Logging.Write(string.Format("[bC]: onstop end ", on));
            //});
            //thread.Start();

        }

        private void onDead()
        {
            using (Styx.StyxWoW.Memory.AcquireFrame())
            {
                data["death"] = Convert.ToInt32(Styx.CommonBot.GameStats.Deaths).ToString();
                data["deathh"] = Convert.ToInt32(Styx.CommonBot.GameStats.DeathsPerHour).ToString();
            }
            Logging.Write("[bC]: Died!");
            if(BuddyConSettings.Instance.notfDied)
                Util.sendToProwl("Died", "Died", data["name"], data["server"]);
            if (!status.ContainsValue("Died!"))
                status.Add("message", "Died!");
            if (BuddyConSettings.Instance.scDied) screenie();

        }

        private void onLevel(BotEvents.Player.LevelUpEventArgs args)
        {

            data["level"] = Convert.ToInt32(Styx.StyxWoW.Me.Level).ToString();

            Logging.Write("[bC]: Level up!");

            if (BuddyConSettings.Instance.notfLevel)
                Util.sendToProwl("Level", "Level up", data["name"], data["server"]);

            if (!status.ContainsValue("Level up!"))
                status.Add("message", "Level up!");
            if (BuddyConSettings.Instance.scLevel) screenie();
        }
        #endregion

        private void uploadscreen(object sender, LuaEventArgs args)
        {
            Lua.Events.DetachEvent("SCREENSHOT_SUCCEEDED", uploadscreen);
            //Logging.Write(string.Format("[bC]: Screenshot Version {0}  {1}", Version.ToString(), BuddyConSettings.Instance.scripturl.Length));
            //Logging.Write("[bC]: Screenshot upload");
            var directory = new DirectoryInfo(wowpath + "\\Screenshots\\");
            string ret = "";
            if(BuddyConSettings.Instance.scripturl.Length>15)
                ret = Util.PostToFtp(directory + Util.GetLatestWritenFileFileInDirectory(directory).ToString());
            else
                ret = Util.PostToImgur(directory + Util.GetLatestWritenFileFileInDirectory(directory).ToString(), "e6b704a473bc5894e03ff99db649e825");

            data["screen"] = ret;
            status.Add("message", "Screenshot sent");
            Logging.Write("[bC]: Screenshot sent");
            send(data,false); 

        }

        private Dictionary<string, string> getData()
        {
            //if (Styx.StyxWoW.IsInGame || Styx.StyxWoW.IsInWorld)
            //{
                try
                {
                    // fill rest data
                    using (Styx.StyxWoW.Memory.AcquireFrame()){
                        if (BuddyConSettings.Instance.debug) Logging.Write(string.Format("[bC]: startAcquireFrame"));

                        data["level"] = Convert.ToInt32(Styx.StyxWoW.Me.Level).ToString();
                        data["faction"] = Styx.StyxWoW.Me.IsAlliance.ToString();

                        if (BuddyConSettings.Instance.pdebug) Logging.Write("[bC]: get server: " + Styx.StyxWoW.Me.RealmName.ToString());
                        //data["runningtime"] = Bots.Gatherbuddy.GatherbuddyBot.runningTime.TotalSeconds.ToString();
                        data["apikey"] = BuddyConSettings.Instance.apikey;
                        data["runningtime"] = (DateTime.Now - startTime).TotalSeconds.ToString();
                        data["xp"] = Convert.ToUInt32(Styx.StyxWoW.Me.Experience).ToString();
                        data["xp_needed"] = Convert.ToUInt32(Styx.StyxWoW.Me.NextLevelExperience).ToString();
                        data["xph"] = Convert.ToUInt32(Styx.CommonBot.GameStats.XPPerHour).ToString();
                        data["timetolevel"] = Convert.ToUInt32(Styx.CommonBot.GameStats.TimeToLevel.TotalSeconds).ToString();

                        data["kills"] = Convert.ToUInt32(Styx.CommonBot.GameStats.MobsKilled).ToString();
                        data["killsh"] = Convert.ToUInt32(Styx.CommonBot.GameStats.MobsPerHour).ToString();

                        data["honor"] = Convert.ToUInt32(Styx.CommonBot.GameStats.HonorGained).ToString();
                        data["honorh"] = Convert.ToUInt32(Styx.CommonBot.GameStats.HonorPerHour).ToString();
                        data["bgwin"] = Convert.ToUInt32(Styx.CommonBot.GameStats.BGsWon).ToString();
                        data["bglost"] = Convert.ToUInt32(Styx.CommonBot.GameStats.BGsLost).ToString();

                        data["gold"] = Convert.ToUInt32(Styx.StyxWoW.Me.Copper).ToString();
                        data["nodeh"] = JSON.JsonEncode(Bots.Gatherbuddy.GatherbuddyBot.NodeCollectionCount);

                        if (BuddyConSettings.Instance.debug) Logging.Write("[bC]: gbankmoney" + data["gbankmoney"]);

                        if (BuddyConSettings.Instance.debug) Logging.Write(string.Format("[bC]: startAcquireFrame end"));

                    }
                }
                catch (Exception e)
                {
                    if (BuddyConSettings.Instance.debug) Logging.Write(string.Format("[bC]: getting error {0} stack: {1}", e.Message, e.StackTrace));
                }
            //}
            return data;
        }
        private void timesUpdater(object sender)
        {
            Dictionary<string, string> dat = (Dictionary<string, string>)sender;
            send(dat,true);
            /*
            if (lastUpdate.AddSeconds(25) < DateTime.Now)
            {
                if (BuddyConSettings.Instance.pdebug) Logging.Write(string.Format("[bC]: times start"));
                if (BuddyConSettings.Instance.debug) Logging.Write(string.Format("[bC]: start update"));

                Dictionary<string, string> dat =getData();
                send(dat);
                if (BuddyConSettings.Instance.pdebug) Logging.Write(string.Format("[bC]: times end"));
                lastUpdate = DateTime.Now;
            }*/
        }
        private void updater()
        {
            if (lastUpdate.AddSeconds(15) < DateTime.Now)
            {
                getData();
                //Thread thread = new Thread(delegate() { 
                    send(data,false); 
                //});
                //thread.Start();
                lastUpdate = DateTime.Now;
            }
        }
        #region Test

        /*

        private void Loot(object sender, LuaEventArgs args)
        {
           
        }
        private void Xp(object sender, LuaEventArgs args)
        {
            if (BuddyConSettings.Instance.debug) Logging.Write(string.Format("[bC]: start xp"));

            
            if (BuddyConSettings.Instance.debug) Logging.Write(string.Format("[bC]: end xp"));

            // Logging.Write(string.Format("[bC]: Xp: {0}", args.Args[0]));
            //Regex r = new Regex("(\\d)+");
            //MatchCollection mc = r.Matches(args.Args[0].ToString());
            //if (BuddyConSettings.Instance.debug) status.Add("message", string.Format("Xp gain"));

        }*/
        #endregion

        #region Chat
        private void Chatter(string message, string author = "", string type = "")
        {
            Logging.Write(string.Format("[bC]: Chat: From: {1}  Message: {0} Type: {2}", message, author, type));
            data["chat_message"] = message;
            data["chat_type"] = type;
            data["chat_from"] = author;

            if (
                (BuddyConSettings.Instance.notfSay && type == "CHAT_MSG_SAY") ||
                (BuddyConSettings.Instance.notfGuild && type == "CHAT_MSG_GUILD") ||
                (BuddyConSettings.Instance.notfBG && (type == "CHAT_MSG_BATTLEGROUND" || type == "CHAT_MSG_BATTLEGROUND_LEADER")) ||
                (BuddyConSettings.Instance.notfRaid && (type == "CHAT_MSG_RAID" || type == "CHAT_MSG_RAID_LEADER")) ||
                (BuddyConSettings.Instance.notfWhisper && type == "CHAT_MSG_WHISPER") 
                )
            {
                if (BuddyConSettings.Instance.debug) Logging.Write("[bC]: send notification");
                Util.sendToProwl("Chat", string.Format("[bC]: Chat: From: {1}  Message: {0} Type: {2}", message, author, type), data["name"], data["server"]);
                if (BuddyConSettings.Instance.androidapi.Length > 10) Util.SendNotification(BuddyConSettings.Instance.androidapi, "{\"from\":\"" + author + "\", \"message\":\"" + message + "\", \"type\":\"" + type + "\"}");
            }
            if (BuddyConSettings.Instance.scChat) screenie();
            //send(data);
        }
        private void BNetWhisper(object sender, LuaEventArgs args)
        {
            if (BuddyConSettings.Instance.debug) Logging.Write(string.Format("[bC]: Chat: From: {1}  Message: {0} Type: {2}", (string)args.Args[0], args.Args[1], args.ToString()));
        }

        private void GMResponse(object sender, LuaEventArgs args)
        {
            if (BuddyConSettings.Instance.debug) Logging.Write(string.Format("[bC]: Chat: From: {1}  Message: {0} Type: {2}", (string)args.Args[0], args.Args[1], args.ToString()));
        }

        private void Chat_Raid(Styx.CommonBot.Chat.ChatLanguageSpecificEventArgs e)
        {
            Thread thread = new Thread(delegate() { Chatter(e.Message, e.Author, e.EventName); });
            thread.Start();
            //Chatter(e.Message, e.Author, e.EventName);
        }

        private void Chat_BG(Styx.CommonBot.Chat.ChatLanguageSpecificEventArgs e)
        {
            Thread thread = new Thread(delegate() { Chatter(e.Message, e.Author, e.EventName); });
            thread.Start();
            //Chatter(e.Message, e.Author, e.EventName);        
        }

        private void Chat_Emote(Styx.CommonBot.Chat.ChatAuthoredEventArgs e)
        {

            Thread thread = new Thread(delegate() { Chatter(e.Message, e.Author, e.EventName); });
            thread.Start();
            //Chatter(e.Message, e.Author, e.EventName);        
        }

        private void Chat_Party(Styx.CommonBot.Chat.ChatLanguageSpecificEventArgs e)
        {
            Thread thread = new Thread(delegate() { Chatter(e.Message, e.Author, e.EventName); });
            thread.Start();
            //Chatter(e.Message, e.Author, e.EventName);        
        }

        private void Chat_Whisper(Styx.CommonBot.Chat.ChatWhisperEventArgs e)
        {
            Thread thread = new Thread(delegate() { Chatter(e.Message, e.Author, e.EventName); });
            thread.Start();
            //Chatter(e.Message, e.Author, e.EventName);        
        }

        private void Chat_Yell(Styx.CommonBot.Chat.ChatLanguageSpecificEventArgs e)
        {
            Thread thread = new Thread(delegate() { Chatter(e.Message, e.Author, e.EventName); });
            thread.Start();
            //Chatter(e.Message, e.Author, e.EventName);        
        }

        private void Chat_Say(Styx.CommonBot.Chat.ChatLanguageSpecificEventArgs e)
        {
            Thread thread = new Thread(delegate() { Chatter(e.Message, e.Author, e.EventName); });
            thread.Start();
            //Chatter(e.Message, e.Author, e.EventName);        
        }

        private void Chat_Guild(Styx.CommonBot.Chat.ChatGuildEventArgs e)
        {
            Thread thread = new Thread(delegate() { Chatter(e.Message, e.Author, e.EventName); });
            thread.Start();
            //Chatter(e.Message, e.Author, e.EventName);        
        }
        #endregion

        
        private void screenie()
        {
            Logging.Write("[bC]: Screenshot requested");
            Lua.Events.AttachEvent("SCREENSHOT_SUCCEEDED", uploadscreen);
            Lua.DoString("TakeScreenshot()");
        }


        private void send(Dictionary<string, string> datax, Boolean onTimer)
        {
            if (!onTimer && BuddyConSettings.Instance.pdebug) Logging.Write(string.Format("[bC]: start sending data {0}", on));
            if (BuddyCon.on && data["server"] != "" && data["apikey"] != "")
            {
                if (!onTimer && BuddyConSettings.Instance.debug) Logging.Write(string.Format("[bC]: start sending data on"));

                if (BuddyConSettings.Instance.pdebug) Logging.Write("[bC]: send server: " + data["server"]);


                try
                {
                    string[] sendParam = new string[datax.Count + 1];
                    string[] sendVal = new string[datax.Count + 1];
                    int i = 0;
                    foreach (var pair in datax)
                    {
                        sendParam[i] = pair.Key;
                        sendVal[i] = pair.Value;
                        i++;
                    }
                    sendParam[i] = "status";
                    sendVal[i] = JSON.JsonEncode(status);
                    status.Clear();

                    string response = "";

                    data["chat_message"] = "";
                    data["chat_type"] = "";
                    data["chat_from"] = "";
                    data["screen"] = "";
                    //data["runningtime"] = "";

                    if (!onTimer && BuddyConSettings.Instance.debug) response = Util.HttpPost("http://localhost/bc/index.php?r=api/mongo", sendParam, sendVal);
                    else if (!onTimer && BuddyConSettings.Instance.ownurl.Length > 7) response = Util.HttpPost(BuddyConSettings.Instance.ownurl, sendParam, sendVal);
                    else response = Util.HttpPost("http://buddyc.eu/index.php?r=api/mongo", sendParam, sendVal);


                    if (!onTimer && BuddyConSettings.Instance.debug) Logging.Write(string.Format("[bC]: sent V{0}", Version.ToString()));
                    if (!onTimer && BuddyConSettings.Instance.debug) Logging.Write(string.Format("[bC]: res {0}", response));

                    if (response != "")
                    {
                        Hashtable resJson = (Hashtable)JSON.JsonDecode(response);

                        switch ((string)resJson["response"])
                        {
                            case "":
                                break;
                            case "success":
                                break;
                            case "killwow":
                                Logging.Write(string.Format("[bC]:  {0}", "Kill Wow requested!"));
                                Styx.StyxWoW.Memory.Process.Kill();
                                break;
                            case "screen":
                                screenie();
                                break;
                            case "chat":
                                sendChat((string)resJson["type"], (string)resJson["message"], (string)resJson["to"]);
                                break;
                            case "stophb":
                                Styx.CommonBot.TreeRoot.Stop();
                                break;
                            case "starthb":
                                Styx.CommonBot.TreeRoot.Start();
                                break;
                            default:
                                Logging.Write(string.Format("[bC]:  {0}", response));
                                break;

                        }
                        if (resJson.ContainsKey("version"))
                        {
                            Logging.Write(string.Format("[bC]: version: {0}", resJson["version"]));
                        }
                    }
                }
                catch (System.InvalidCastException e)
                {
                    if (BuddyConSettings.Instance.debug) Logging.Write(string.Format("[bC]: error cast {0}", e.Message));
                }
                catch (Exception e)
                {
                    if (BuddyConSettings.Instance.debug) Logging.Write(string.Format("[bC]: error send {0}", e.Message));
                }


                if (!onTimer && BuddyConSettings.Instance.pdebug) Logging.Write(string.Format("[bC]: end sending data"));
            }
            else
            {
                if(!on)
                    times.Dispose(); 

                if(data["server"] == "" || data["apikey"] == "")
                    Logging.Write(string.Format("[bC]: Error server or apikey not set " + data["server"]));
            }
            
        }

        private void sendChat(string type, string message, string to)
        {
            Lua.DoString("SendChatMessage(\""+message+"\", \""+type+"\", nil, \""+to+"\");");
            Logging.Write(string.Format("[bC]: send Chat channel: {0} Message: {1} To:{2}", type,message,to));
            
        }
    }
}
